package IOoperation;

import java.io.*;
import java.util.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import com.thoughtworks.xstream.*;
import core.Coordinate;
import factory.ComponentFactory;
import factory.ComponentInterface;
import factory.CreatComponent;

public class XMLcontroler {

	public XMLcontroler() {
	}
	/**
	 * Lementi a terkepet egy xml file-ba
	 * @param list
	 * 			a lista amibe le vannak mentve a komponensek
	 * @param fileName
	 * 			a file neve amibe le lesz mentve a terkep
	 */
	public void exportToXml(List<ComponentInterface> list, String fileName) {
		XStream xs = new XStream();
		try {
			FileWriter xmlFile = new FileWriter(fileName);
			xmlFile.write("<?xml version=\"1.0\"?>\n");
			xmlFile.write("<JavaRoadEditor>\n");
			xmlFile.close();
			FileOutputStream fs = new FileOutputStream(fileName, true);
			ListIterator<ComponentInterface> li = list.listIterator();
			while (li.hasNext()) {
				xmlFile = new FileWriter(fileName, true);
				xmlFile.write("<Komponens>\n");
				xmlFile.close();
				xs.toXML(li.next(), fs);
				xmlFile = new FileWriter(fileName, true);
				xmlFile.write("\n</Komponens>\n");
				xmlFile.close();
			}
			xmlFile.close();
			fs.close();
			xmlFile = new FileWriter(fileName, true);
			xmlFile.write("\n</JavaRoadEditor>");
			xmlFile.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	/**
	 * Felvagja a kapott stringet.
	 * @param s 
	 * 		a komponens class - nevet tartalmazza
	 * @return visszateriti a komponens nevet
	 */
	private String tokenizer(String s) {
		String tokenN = null;
		String tokenNN = null;
		StringTokenizer st = new StringTokenizer(s, ".");
		while (st.hasMoreElements()) {
			String token = st.nextToken();
			tokenN = token;
		}
		StringTokenizer st2 = new StringTokenizer(tokenN, ":");
		tokenNN = st2.nextToken();
		return tokenNN;
	}
	/**
	 * Betolti az xml file-ban tarolt terkepet.
	 * @param fileName
	 * 			a file neve amibol betoltjuk a terkepet
	 * @return visszaterit egy listat ami tartalmazni fogja a komponenseket
	 */
	public List<ComponentInterface> importFromXml(String fileName) {
		List<ComponentInterface> listcomp = new ArrayList<ComponentInterface>();
		try {
			BufferedReader bf = new BufferedReader(new FileReader(fileName));
			File file = new File(fileName);
			if (file.exists()) {
				// Create a factory
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				// Use the factory to create a builder
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(fileName);
				bf.readLine();
				String Fejlec = bf.readLine();
				if (!Fejlec.equals("<JavaRoadEditor>"))
					throw new Exception();
				else {

					// Get a list of all elements in the document
					NodeList list = doc.getElementsByTagName("Komponens");
					System.out.println("XML Elements: ");
					System.out.println(list.getLength());

					for (int i = 0; i < list.getLength(); i++) {
						Node compLst = list.item(i);

						Element elem = (Element) compLst; // get name
						NodeList factLst = elem.getChildNodes();
						String nameTxt;
						nameTxt = tokenizer(factLst.item(1).toString());
						System.out.println("Name : " + nameTxt);

						Integer orient = -100;
						int orientation = 0;
						NodeList orientLst = elem
						.getElementsByTagName("orientation"); // get
						// orientation
						if (orientLst.getLength() != 0) {
							Element orientElmnt = (Element) orientLst.item(0);
							NodeList orientVal = orientElmnt.getChildNodes();
							orient = Integer.parseInt(((Node) orientVal.item(0))
									.getNodeValue());
							if (orient != -100) {
								orientation = orient.intValue();
								System.out.println("Orientation : " + orient);
							}
						}

						NodeList posElmntLst = elem // get position
						.getElementsByTagName("position");
						Element posElmnt = (Element) posElmntLst.item(0);
						NodeList xLst = posElmnt.getElementsByTagName("x"); // get
						// coordinate
						// X
						Element xElmnt = (Element) xLst.item(0);
						NodeList x = xElmnt.getChildNodes();
						int xValP = Integer.parseInt(((Node) x.item(0))
								.getNodeValue());
						System.out.println("POSITION : X erteke: " + xValP);
						NodeList yLst = posElmnt.getElementsByTagName("y"); // get
						// coordinate
						// Y
						Element yElmnt = (Element) yLst.item(0);
						NodeList y = yElmnt.getChildNodes();
						int yValP = Integer.parseInt(((Node) y.item(0))
								.getNodeValue());
						System.out.println("POSITION : Y erteke: " + yValP);

						NodeList sizeElmntLst = elem.getElementsByTagName("size"); // get
						// size
						Element sizeElmnt = (Element) sizeElmntLst.item(0);
						NodeList xsLst = sizeElmnt.getElementsByTagName("x"); // get
						// coordinate
						// X
						Element xsElmnt = (Element) xsLst.item(0);
						NodeList xs = xsElmnt.getChildNodes();
						int xValS = Integer.parseInt(((Node) xs.item(0))
								.getNodeValue());
						System.out.println("SIZE : X erteke: " + xValS);
						NodeList ysLst = sizeElmnt.getElementsByTagName("y"); // get
						// coordinate
						// Y
						Element ysElmnt = (Element) ysLst.item(0);
						NodeList ys = ysElmnt.getChildNodes();
						int yValS = Integer.parseInt(((Node) ys.item(0))
								.getNodeValue());
						System.out.println("SIZE : Y erteke: " + yValS);

						if (nameTxt.equals("Building")) // build the list
						{
							ComponentFactory comp = new CreatComponent();
							ComponentInterface building = comp.creatBuilding();
							building.setPosition(new Coordinate(xValP, yValP));
							building.setSize(new Coordinate(xValS, yValS));
							building.setOrientation(orientation);
							listcomp.add(building);
						}
						if (nameTxt.equals("Earth")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface earth = comp.creatEarth();
							earth.setPosition(new Coordinate(xValP, yValP));
							earth.setSize(new Coordinate(xValS, yValS));
							earth.setOrientation(orientation);
							listcomp.add(earth);
						}
						if (nameTxt.equals("Gate")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface gate = comp.creatGate();
							gate.setPosition(new Coordinate(xValP, yValP));
							gate.setSize(new Coordinate(xValS, yValS));
							gate.setOrientation(orientation);
							listcomp.add(gate);
						}
						if (nameTxt.equals("QuaryCrane")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface quaryCrane = comp.creatQuaryCrane();
							quaryCrane.setPosition(new Coordinate(xValP, yValP));
							quaryCrane.setSize(new Coordinate(xValS, yValS));
							quaryCrane.setOrientation(orientation);
							listcomp.add(quaryCrane);
						}
						if (nameTxt.equals("RailMountedGantry")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface railMountedGantry = comp
							.creatRailMountedGantry();
							railMountedGantry.setPosition(new Coordinate(xValP,
									yValP));
							railMountedGantry.setSize(new Coordinate(xValS, yValS));
							railMountedGantry.setOrientation(orientation);
							listcomp.add(railMountedGantry);
						}
						if (nameTxt.equals("ReachStacker")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface reachStacker = comp
							.creatReachStacker();
							reachStacker.setPosition(new Coordinate(xValP, yValP));
							reachStacker.setSize(new Coordinate(xValS, yValS));
							reachStacker.setOrientation(orientation);
							listcomp.add(reachStacker);
						}
						if (nameTxt.equals("RoadTruck")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface roadTruck = comp.creatRoadTruck();
							roadTruck.setPosition(new Coordinate(xValP, yValP));
							roadTruck.setSize(new Coordinate(xValS, yValS));
							roadTruck.setOrientation(orientation);
							listcomp.add(roadTruck);
						}
						if (nameTxt.equals("RubberTiredGantry")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface rubberTiredGantry = comp
							.creatRubberTiredGantry();
							rubberTiredGantry.setPosition(new Coordinate(xValP,
									yValP));
							rubberTiredGantry.setSize(new Coordinate(xValS, yValS));
							rubberTiredGantry.setOrientation(orientation);
							listcomp.add(rubberTiredGantry);
						}
						if (nameTxt.equals("Stack")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface stack = comp.creatStack();
							stack.setPosition(new Coordinate(xValP, yValP));
							stack.setSize(new Coordinate(xValS, yValS));
							stack.setOrientation(orientation);
							listcomp.add(stack);
						}
						if (nameTxt.equals("StraddleCarrier")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface straddleCarrier = comp
							.creatStraddleCarrier();
							straddleCarrier
							.setPosition(new Coordinate(xValP, yValP));
							straddleCarrier.setSize(new Coordinate(xValS, yValS));
							straddleCarrier.setOrientation(orientation);
							listcomp.add(straddleCarrier);
						}
						if (nameTxt.equals("TerminalTruck")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface terminalTruck = comp
							.creatTerminalTruck();
							terminalTruck.setPosition(new Coordinate(xValP, yValP));
							terminalTruck.setSize(new Coordinate(xValS, yValS));
							terminalTruck.setOrientation(orientation);
							listcomp.add(terminalTruck);
						}
						if (nameTxt.equals("Vessel")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface vessel = comp.creatVessel();
							vessel.setPosition(new Coordinate(xValP, yValP));
							vessel.setSize(new Coordinate(xValS, yValS));
							vessel.setOrientation(orientation);
							listcomp.add(vessel);
						}
						if (nameTxt.equals("Water")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface water = comp.creatWater();
							water.setPosition(new Coordinate(xValP, yValP));
							water.setSize(new Coordinate(xValS, yValS));
							water.setOrientation(orientation);
							listcomp.add(water);
						}
						if (nameTxt.equals("Terminal")) {
							ComponentFactory comp = new CreatComponent();
							ComponentInterface terminal = comp.creatTerminal();
							terminal.setPosition(new Coordinate(xValP, yValP));
							terminal.setSize(new Coordinate(xValS, yValS));
							terminal.setOrientation(orientation);
							listcomp.add(terminal);
						}
					} //for
				}
			}//if
			else {
				System.out.print("File not found!");
			}
		}

		catch (Exception e){
			System.out.println("No file selected");
		}
		ListIterator<ComponentInterface> li = listcomp.listIterator();
		while(li.hasNext()){
			ComponentInterface co = li.next();
			System.out.println(co.getOrientation()+ " " + co);
		}
		return listcomp;
	}
}